package xyz.zq.sf.common.core.config;

import cn.hutool.core.date.DatePattern;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.Parser;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import xyz.zq.sf.common.core.util.LocalDateTimeUtil;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;

import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type.SERVLET;

/**
 * Web Mvc配置
 *
 * @author hzq
 * @date 2021-01-27 16:13
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = SERVLET)
public class WebMvcConfiguration implements WebMvcConfigurer {

    /**
     * @param registry 格式器注册表
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        setDateTimeFormatterRegistrar(registry);
    }

    /**
     * 配置日期时间格式注册器
     * 对所有以表单方式提交的日期类型进行转换
     * Content-type:form-data、urlEncode
     *
     * @param registry 格式器注册表
     */
    protected void setDateTimeFormatterRegistrar(FormatterRegistry registry) {
        /*日期时间格式注册器*/
        DateTimeFormatterRegistrar tfr = new DateTimeFormatterRegistrar();
        tfr.setTimeFormatter(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN));
        tfr.setDateFormatter(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
        tfr.registerFormatters(registry);
        registry.addParser(new StrToDateParser());
        registry.addParser(new StrToLocalDateParser());
        registry.addParser(new StrToLocalDateTimeParser());
    }

    /**
     * String to Date
     * 字符串解析成日期类型
     */
    public static class StrToDateParser implements Parser<Date> {

        @Override
        public Date parse(String text, Locale locale) {
            return LocalDateTimeUtil.parseStrToDate(text, Date.class);
        }
    }

    /**
     * String to LocalDate
     * 字符串解析成日期类型
     */
    public static class StrToLocalDateParser implements Parser<LocalDate> {

        @Override
        public LocalDate parse(String text, Locale locale) {
            return LocalDateTimeUtil.parseStrToDate(text, LocalDate.class);
        }
    }

    /**
     * String to LocalDateTime
     * 字符串解析成日期类型
     */
    public static class StrToLocalDateTimeParser implements Parser<LocalDateTime> {

        @Override
        public LocalDateTime parse(String text, Locale locale) {
            return LocalDateTimeUtil.parseStrToDate(text, LocalDateTime.class);
        }
    }
}
